import os
from pathlib import Path
from unicodedata import name
from app.libs.enums import RType
from app.libs.forms import UploadByPathForm
from app.libs.utils import HttpHelper
from app.ro import CreateRemoteDirParam
from app.service.chapter import ChapterService
from app.vo import FailCourseVO
from .base import BaseService
import filetype


class CourseService(BaseService):

    @classmethod
    def upload_by_path(cls, form: UploadByPathForm):
        return cls.upload(form.path.data, form.vsConfigForm.data)

    @classmethod
    def upload(cls, course_dir, vsConfig: dict):
        course_dir = Path(course_dir)

        def createRemoteDir():
            # 创建文件夹 获取 章节 id
            chapter_name = os.path.basename(course_dir)
            param = CreateRemoteDirParam().set_attrs(dict(
                name=chapter_name,
                type=RType.COURSE.value
            ))
            # 发起请求
            url = '/v1/resource/create/pure'
            resp = HttpHelper.post(url, param)
            # 获取返回结果中的内容
            course_id = resp.content_object['id']
            course_name = resp.content_object['name']
            return course_id, course_name

        # 创建远程目录
        course_id, course_name = createRemoteDir()
        # 准备章节列表
        chapter_paths = course_dir.glob('*')
        chapter_paths = [ch_path for ch_path in chapter_paths
                         if cls.includeVideo(ch_path)]

        # 循环上传内容
        # 记录失败列表
        fail_courses_vo = FailCourseVO(dict(
            name=course_name,
            dir=course_dir,
            fail_chapters=[]
        ))
        for ch_dir in chapter_paths:
            fail_chapters_vo = ChapterService.upload(
                chapter_dir=ch_dir,
                vsConfig=vsConfig,
                course_id=course_id,
                course_name=course_name
            )
            if len(fail_chapters_vo.fail_videos) > 0:
                fail_courses_vo.fail_chapters.append(fail_chapters_vo)
        return fail_courses_vo

    @staticmethod
    def includeVideo(path_dir:  Path) -> bool:
        """ 判断某个文件夹下方是否有视频 """
        path_dir = Path(path_dir)
        if not path_dir.is_dir():
            return False
        for item in path_dir.iterdir():
            if item.is_file() and filetype.is_video(str(item)):
                return True
        return False
